﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using Kugar.Core.ExtMethod;

namespace Kugar.MVC.MobileUI.WeUI.Helpers
{
    public class OptionHelper
    {
        private static ConcurrentDictionary<Type,SelectorItem[]> _enumConvertCache=new ConcurrentDictionary<Type, SelectorItem[]>();

        public static IEnumerable<SelectorItem> Convert<T>(IEnumerable<T> source, Func<T, string> titleFunc,
            Func<T, string> valueFunc)
        {
            foreach (var item in source)
            {
                yield return new SelectorItem(titleFunc(item), valueFunc(item));
            }
        }

        public static IEnumerable<SelectorItem> Convert(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new ArrayTypeMismatchException("enumType参数类型必须为枚举类型");
            }

            return _enumConvertCache.GetOrAdd(enumType, x =>
            {
                var names = x.GetEnumNames();
                var values = (int[]) x.GetEnumValues();
                var lst = new List<SelectorItem>(names.Length);

                for (int i = 0; i < names.Length; i++)
                {
                    FieldInfo enumInfo = x.GetField(names[i]);

                    var a = (DescriptionAttribute) enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false)
                        .FirstOrDefault();

                    var k = new SelectorItem(a != null ? a.Description : names[i].ToStringEx(), values[i].ToString());

                    lst.Add(k);
                }

                return lst.ToArrayEx();
            });


        }
    }
}